import axios from "axios";
import loadingQuene from "./LoadingQuene";
import Storage from "@/utils/localStorage";
import { Toast } from "vant";

const STORAGE_TOKEN_KEY = "fty_partner_token";
storeToken();

axios.defaults.headers.common = {
  "X-Requested-With": "XMLHttpRequest",
  "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
};

axios.interceptors.request.use(function (request) {
  //携带token请求接口
  request.headers.common["cookiekey"] = Storage.get(STORAGE_TOKEN_KEY);
  return request;
});

axios.interceptors.response.use(
  function (response) {
    if (!response) {
      return Promise.reject({
        msg: "网络不给力!",
        error: 1,
      });
    }
    try {
      // 结束当前请求的loading
      let url = response.config.url;
      loadingQuene.dequene(url);

      var query = getParams(window.location.href);
      if (query.uid) {
        window.localStorage.setItem("uid", true);
      }

      let res = response.data;
      //error [0:正常成功 1:失败 9998:登录失效]
      if (res.error === 0) {
        return Promise.resolve(res);
      } else if (res.error === 9998) {
        return Promise.reject(res);
      } else {
        console.log("err res:", res);
        alert(res.msg || "请求失败");
        return Promise.reject(response);
      }
    } catch (err) {
      console.log("response err:", response, err);
    }
  },
  function (error) {
    alert(JSON.stringify(error));

    // if (error.response && error.response.status) {
    //   switch (error.response.status) {
    //     case 404:
    //       router.push({ name: "404" });
    //       break;
    //     case 503:
    //       router.push({ name: "503" });
    //       break;
    //     default:
    //       console.log(error.response);
    //       break;
    //   }
    // }
    return Promise.reject(error);
  }
);

function getParams(str) {
  let q = {};
  str.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => (q[k] = v));
  return q;
}

function storeToken(tokenKey='token') {
  var query = getParams(window.location.href);
  if (query[tokenKey]) {
    Storage.set(STORAGE_TOKEN_KEY, query[tokenKey]);
  } else {
    Toast.fail("未获取到用户授权信息");
  }
}

function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return arr[2];
  else return "";
}

function setCookie(
  name,
  value,
  days = 15,
  domain = window.location.host,
  path = "/"
) {
  var exp = new Date();
  exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
  document.cookie = `${name}=${value};expires=${exp.toUTCString()};path=${path};domain=${domain}`;
}

/**
 * API请求分发器
 * @param {Object} options {}
 * @param {string} .method 请求方法 get | post，默认为get
 * @param {string} .url 请求地址
 * @param {object} .params 请求参数，默认{}
 * @param {boolean} .loading 是否需要请求loading
 * @returns AxiosPromise
 */
function dispatcher(
  options = { method: "get", url: "/", params: {}, loading: false }
) {
  const { method = "get", url = "/", params = {}, loading = false } = options;
  if (loading) {
    loadingQuene.enquene(url, { ...params });
  }
  switch (method.toLowerCase()) {
    case "get":
      return get(url, params);
    case "post":
      return post(url, params);
    default:
      throw new Error("wrong request method");
  }
}

function get(url, params) {
  return axios({
    method: "get",
    url,
    params,
  });
}

function post(url, params) {
  return axios({
    method: "post",
    url,
    data: params,
  });
}

export { axios, get, post, dispatcher };
